<template>
  <div class="semester_box" v-loading="loading">
    <div class="semester_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        新增学期
      </el-button>
    </div>
    <el-table
      :data="semesterDatas?.list"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
    >
      <el-table-column align="center" label="ID" min-width="50" prop="id" />
      <el-table-column
        align="center"
        label="学期名"
        min-width="120"
        prop="name"
      />
      <el-table-column
        align="center"
        label="开学时间"
        min-width="120"
        prop="startTime"
      />
      <el-table-column
        align="center"
        label="周数"
        min-width="120"
        prop="weekNum"
      />
      <el-table-column
        align="center"
        label="创建时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="edit"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否删除该学期?"
            @confirm="deleteSemesterById(scope.row.id)"
          >
            <template #reference>
              <el-button type="primary" link icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="semesterPageParmas.pageNum"
      v-model:page-size="semesterPageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 320px"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="semesterForms"
        :inline="true"
        :model="semesterForm"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="学期名name" prop="name" style="width: 55%">
          <el-input v-model="semesterForm.name" placeholder="请输入学期名" />
        </el-form-item>
        <el-form-item label="开学时间" prop="startTime" style="width: 55%">
          <el-date-picker
            v-model="semesterForm.startTime"
            type="date"
            placeholder="请输入开学时间"
          />
        </el-form-item>
        <el-form-item label="周数weekNum" prop="weekNum" style="width: 55%">
          <el-input-number
            v-model="semesterForm.weekNum"
            placeholder="请输入周数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm(semesterForms)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  SemesterParams,
  BasePageQuery,
  SemesterPageRes,
  SemesterType,
} from '@/api/semester/type'
import {
  reqAddSemester,
  reqDeleteSemesterById,
  reqGetSemesterPage,
  reqUpdateSemester,
} from '@/api/semester'

onMounted(async () => {
  await getSemesterInfoPage()
})

const dialogFormVisible = ref<boolean>(false)
const semesterPageParmas: BasePageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const semesterDatas = ref<SemesterPageRes>()
const total = ref(0)
const loading = ref(false)

const semesterForms = ref<FormInstance>()
let semesterForm: SemesterParams = reactive({
  id: 0,
  name: '',
  startTime: '',
  weekNum: 0,
})

const rules = reactive({
  name: [{ required: true, message: '请输入学期名', trigger: 'blur' }],
  startTime: [{ required: true, message: '请输入开学时间', trigger: 'blur' }],
  weekNum: [{ required: true, message: '请输入周数', trigger: 'blur' }],
})

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('新增学期')
const isEdit = ref(false)

const getSemesterInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetSemesterPage(semesterPageParmas)
    semesterDatas.value = data
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const deleteSemesterById = async (id: number) => {
  try {
    const { message } = await reqDeleteSemesterById(id)
    ElMessage.success(message)
    await getSemesterInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const addSemester = async () => {
  try {
    const { message } = await reqAddSemester(semesterForm)
    ElMessage.success(message)
    semesterForm = {
      id: 0,
      name: '',
      startTime: '',
      weekNum: 0,
    }
    await getSemesterInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const updateSemester = async () => {
  try {
    const { message } = await reqUpdateSemester(semesterForm)
    ElMessage.success(message)
    await getSemesterInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateSemester()
      } else {
        addSemester()
      }
      dialogFormVisible.value = false
    }
  })
}

const openAddDialog = () => {
  isEdit.value = false
  if (semesterForm.id !== 0) {
    semesterForm = {
      id: 0,
      name: '',
      startTime: '',
      weekNum: 0,
    }
  }
  dialogTitle.value = '新增学期'
  dialogFormVisible.value = true
}
// 修改菜单方法
const openEditDialog = async (data: SemesterType) => {
  isEdit.value = true
  dialogTitle.value = '编辑学期'
  semesterForm.id = data.id
  semesterForm.name = data.name
  semesterForm.startTime = data.startTime
  semesterForm.weekNum = data.weekNum
  dialogFormVisible.value = true
}

const handleSizeChange = (val: number) => {
  getSemesterInfoPage()
}
const handleCurrentChange = (val: number) => {
  getSemesterInfoPage()
}
</script>
<style scoped lang="scss">
.semester_box {
  padding: 24px;

  .semester_addbtn {
    margin-bottom: 12px;
    display: flex;
  }
}
</style>
